import { loginSystem, buyOrSale } from '../services/indexPage';
import { notification } from 'antd';
import { routerRedux } from 'dva/router';
export default {
  namespace : 'navigation',
  state : {
    isLogin : !!localStorage.getItem("login"),
    administrator : localStorage.getItem("level") === 0,
    visible : false,
    type : 0,
    loding : false
  },
  subscriptions : {
  },
  effects : {
    *login({ payload }, { call, put }){
      yield put({ type: "showLoading" })
      const { data } = yield call(loginSystem,payload);
      if(data.code === 201){
        notification.success({
          description : data.info,
          message : "登陆系统"
        })
        localStorage.setItem("login",true)
        localStorage.setItem("level",data.level)
        yield put(routerRedux.push("/home"))
        yield put({ type : "loginSuccess" })
      }else if(data.code === 300){
        notification.error({
          description : data.info,
          message : "登陆系统"
        })
      }
      yield put({ type:'hideLoading'})
    },
    *buyOrSale({ payload }, { call, put }) {
      const { data: b } = yield call(buyOrSale, payload);
      yield put({ type : "hideModal" })
      if(b.code === 201){
        notification.success({
          description : b.info,
          message : "买入/卖出"
        })
        yield put(routerRedux.replace("/"))
      }else if(b.code === 300){
        notification.error({
          description : b.info,
          message : "买入/卖出"
        })
      }
    },
    *signOutSystem(_,{ put, call }){
      localStorage.clear()
      yield put({type : "navigation/outSystem"})
      notification.success({
        description : "退出登录",
        message : "系统提示"
      })
    }
  },
  reducers : {
    showModal(state, { payload }) {
      return {
        ...state,
        visible : true,
        type : payload
      }
    },
    hideModal(state) {
      return {
        ...state,
        visible : false
      }
    },
    loginSuccess(state) {
      return {
        ...state,
        isLogin : true 
      }
    },
    showLoading(state) {
      return {
        ...state,
        loading : true
      }
    },
    hideLoading(state) {
      return {
        ...state,
        loading : false
      }
    },
    outSystem(state){
      return {
        ...state,
        isLogin : false
      }
    }
  }
}